/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.lottery.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.lottery.entity.LotteryRecord;
import com.wealth.lottery.service.ILotteryRecordService;
import com.wealth.lottery.vo.LotteryRecordVo;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

import iaas.enums.StatusEnum;
import iaas.excel.ExcelUtil;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Controller
@RequestMapping(value="/manage/lottery/record")
public class RecordController extends BaseController{

	Logger logger = Logger.getLogger(RecordController.class);
	
	@Autowired
	private ILotteryRecordService recordService;
	
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder){
		//注册自定义的属性编辑器，适合日期
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		// 表示如果命令对象有Date类型的属性，将使用该属性编辑器进行类型转换
		binder.registerCustomEditor(Date.class, dateEditor);
	}
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try{
			if (id != -1) {
				LotteryRecord record = recordService.get(id);
				model.addAttribute("record", record);
			}
		}catch(Exception e){
			logger.error("初始化错误", e);
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(Model model){
		Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
		model.addAttribute("corpid", corpid);
		return "lotteryRecord/list";
	}
	
	
	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value="/list",method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model,JqGridRequest request) {
		try{

			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			
			Page<LotteryRecord> page = recordService.get(corpid, request,LotteryRecord.class);
			
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表错误！", e);
			return null;
		}
	}
	
	
	/**
	 * 详情
	 */
	@RequestMapping(value="/{id}",method = RequestMethod.GET)
	public String infoForm(Model model,@PathVariable("id") Long id){
		try{
			LotteryRecord record = recordService.get(id);
			model.addAttribute("record", record);
			return "lottery/record/info";
		}catch(Exception e){
			logger.error("详情页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	
	/**
	 * 创建页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(){
		try {
			return "lottery/record/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 创建
	 */
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,LotteryRecord entity,RedirectAttributes redirectAttributes){
		try {
			User user = ShiroUser.getInstance().getUser();
			
			entity.setStatus(StatusEnum.NORMAL.getValue());
			entity.setCorp(user.getCorp());
			entity.setCreateTime(new Date());
			entity.setCreator(user.getUsername());
			recordService.save(entity);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/lottery/record/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String setUpdateForm(Model model,@PathVariable("id") Long id){
		try{
			LotteryRecord record = recordService.get(id);
			model.addAttribute("record", record);
			return "lottery/record/update";
		}catch(Exception e){
			logger.error("编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 修改信息
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,@ModelAttribute("record") LotteryRecord record,RedirectAttributes redirectAttributes){
		try{
			recordService.save(record);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("编辑成功"));
			return "redirect:/manage/lottery/record/list";
		}catch(Exception e){
			logger.error("编辑错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String delete(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			recordService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/lottery/record/list";
		}catch(Exception e){
			logger.error("删除错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 停用
	 */
	@RequestMapping(value="/disable/{id}",method = RequestMethod.GET)
	public String disable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			recordService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/lottery/record/list";
		}catch(Exception e){
			logger.error("停用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value="/enable/{id}",method = RequestMethod.GET)
	public String enable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			recordService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/lottery/record/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	
	/**
	 * 导出订单信息
	 */
	@RequestMapping(value="export",method=RequestMethod.GET)
	public void outOrderInfo(Model model,HttpServletResponse response,HttpServletRequest request){
		
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			List<LotteryRecord> recordList = recordService.getLotteryRecordByCorpId(corpid);
			List<LotteryRecordVo> voList = new ArrayList<LotteryRecordVo>();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (LotteryRecord record : recordList) {
				LotteryRecordVo vo = new LotteryRecordVo();
				vo.setCreateTime(format.format(record.getCreateTime()));
				vo.setMobile(record.getMember().getUsername());
				vo.setNickName(record.getMember().getNickname());
				if(record.getPrize()!=null){
					vo.setPrizeName(record.getPrize().getName());
					if(record.getPrize().getLevel()==0){
						vo.setPrizeLevel("一等奖");
					}else if(record.getPrize().getLevel()==1){
						vo.setPrizeLevel("二等奖");
					}else if(record.getPrize().getLevel()==2){
						vo.setPrizeLevel("三等奖");
					}else if(record.getPrize().getLevel()==3){
						vo.setPrizeLevel("四等奖");
					}
				}else{
					vo.setPrizeName("谢谢参与");
					vo.setPrizeLevel("参与奖");
				}	
				voList.add(vo);
			}
			LinkedHashMap<String,String> fieldMap = new LinkedHashMap<String, String>();
			fieldMap.put("prizeLevel", "奖品等级");
			fieldMap.put("prizeName", "奖品名称");
			fieldMap.put("nickName", "中奖人");
			fieldMap.put("mobile", "手机号码");
			fieldMap.put("createTime", "中奖时间");
			ExcelUtil.listToExcel(voList, fieldMap, "中奖列表", response);
/*		Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();	
		List<Order> orderList=orderService.findorderByCorpId(corpid);
		List<OrderVO> ordVoList = new ArrayList<OrderVO>();
		for (Order order : orderList) {
			OrderVO ordervo =  new OrderVO();
			ordervo.setId(order.getId());
			if(StringUtils.isNotBlank(order.getMember().getFans().getName())){
				ordervo.setMemberName(order.getMember().getFans().getName());
			}else{
				ordervo.setMemberName(order.getMember().getFans().getNickname());
			}
			
			ordervo.setGoodsName(order.getGoods().getName());
			ordervo.setOrderNo(order.getOrderno());
			ordervo.setAmount(order.getAmount());
			ordervo.setTotal(order.getTotal());
			ordervo.setLogisticsName(order.getLogisticsname());
			ordervo.setLogisticsNo(order.getLogisticsno());
			ordervo.setConsignee(order.getConsignee());
			ordervo.setAddress(order.getAddress());
			ordervo.setMobilel(order.getMobile());
			ordervo.setCropName(order.getCorp().getName());
			if(order.getStatus()==OrderStatusEnum.DELETE.getValue()){
				ordervo.setStatus("已删除");
			}else if(order.getStatus()==OrderStatusEnum.PAY.getValue()){
				ordervo.setStatus("已支付");
			}else{
				ordervo.setStatus("已发货");
			}
			ordervo.setCreateTime(order.getCreatetime());
		    ordVoList.add(ordervo);
		}
		LinkedHashMap<String,String> fieldMap = new LinkedHashMap<String, String>();
		fieldMap.put("id", "id");
		fieldMap.put("memberName", "兑换人姓名");
		fieldMap.put("goodsName", "兑换人礼品");
		fieldMap.put("orderNo", "订单编号");
		fieldMap.put("amount", "兑换数量");
		fieldMap.put("total", "兑换积分");
		fieldMap.put("logisticsName", "快递公司");
		fieldMap.put("logisticsNo", "快递编号");
		fieldMap.put("consignee", "收货人");
		fieldMap.put("address", "收货地址");
		fieldMap.put("mobilel", "收货人电话");
		fieldMap.put("cropName", "企业名称");
		fieldMap.put("status", "订单状态");
		fieldMap.put("createTime", "创建时间");
		ExcelUtil.listToExcel(ordVoList, fieldMap, "订单表", response);*/
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
}